package com.kui.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.kui.common.ResultUtils;
import com.kui.config.CosClientConfig;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import com.kui.model.dto.file.UploadPictureResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *  已弃用该服务
 */
@Service
@Slf4j
@Deprecated
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;

    /**
     * 图片上传
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 1.校验图片
        validPicture(multipartFile);
        // 2.图片上传地址
        // 防止重复设置uuid
        String uuid = RandomUtil.randomString(16);
        // 拿到原文件命
        String originalFilename = multipartFile.getOriginalFilename();
        // 拼接上传文件名
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        // 拼接上传路径
        String uploadFilePath = String.format("%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            // 将文件保存到临时文件中
            multipartFile.transferTo(file);
            // 获取到图片信息
            PutObjectResult putObjectResult = cosManager.puPictureObject(uploadFilePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            // 返回可访问地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("file upload error, filePath = ", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            deleteTempFile(file, uploadFilePath);
        }
    }

    /**
     * 通过url地址上传图片
     *
     * @param url
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPictureByUrl(String url, String uploadPathPrefix) {
        //  1.检验
        validPicture(url);
        // 2.图片上传地址
        String uuid = RandomUtil.randomString(16);
        // 3.通过url拿到文件的原名称
        String originalFilename = FileUtil.mainName(url);
        // 4.拼接上传文件名
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
        // 5.拼接上传路径
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(uploadFilePath, null);
            // 下载文件
            HttpUtil.downloadFile(url, file);
            // 上传图片
            PutObjectResult putObjectResult = cosManager.putObject(uploadFilePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadFilePath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(picWidth);
            uploadPictureResult.setPicHeight(picHeight);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            // 返回可访问地址
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("file upload error, filePath = ", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            deleteTempFile(file, uploadFilePath);
        }
    }

    /**
     * 校验图片
     *
     * @param multipartFile
     */
    public void validPicture(MultipartFile multipartFile) {
        // 1.校验图片是否存在
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "图片不存在");
        // 2.校验图片大小
        long multipartFileSize = multipartFile.getSize();
        // 定义1MB大小的常量
        final long maxFileSize = 1024 * 1024;
        ThrowUtils.throwIf(multipartFileSize > 2 * maxFileSize, ErrorCode.PARAMS_ERROR, "图片大小不能超过2MB");
        // 3.校验图片格式
        // 拿到文件的后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 定义允许上传的后缀列表
        final List<String> allowSuffix = Arrays.asList("png", "jpg", "jpeg", "bmp", "gif", "webp");
        ThrowUtils.throwIf(!allowSuffix.contains(suffix), ErrorCode.PARAMS_ERROR, "图片格式不支持");
    }

    /**
     * 通过url进行图片的校验
     *
     * @param url
     */
    public void validPicture(String url) {
        ThrowUtils.throwIf(StrUtil.isBlank(url), ErrorCode.NOT_FOUND_ERROR, "文件地址不为空");
        // 1.验证url格式
        try {
            // 验证是否为合法的url格式
            new URL(url);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式错误");
        }
        // 2.校验URL协议
        ThrowUtils.throwIf(!(url.startsWith("http://") || url.startsWith("https://")), ErrorCode.PARAMS_ERROR, "文件地址协议错误");
        // 3.发送HEAD请求，验证文件是否存在
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, url).execute();
            // 未正常返回，则返回不需要继续执行后面的判断
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }
            // 检验文件的类型
            String contentType = response.header("Content-Type");
            if (StrUtil.isNotBlank(contentType)) {
                // 定义允许上传的文件类型
                final List<String> allowContentType = Arrays.asList("image/png", "image/jpeg", "image/jpg", "image/bmp", "image/gif", "image/webp");
                ThrowUtils.throwIf(!allowContentType.contains(contentType), ErrorCode.OPERATION_ERROR, "文件上传类型不支持");
            }
            // 检验文件的大小
            String contentLengthStr = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLengthStr)) {
                try {
                    final long TWO_MB = 1024 * 1024 * 2L; // 设置常量为2MB
                    // 将获取到的文件大小字符串转换为long类型方便后续比较
                    long contentLength = Long.parseLong(contentLengthStr);
                    ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

    /**
     * 删除临时文件
     *
     * @param file
     * @param filePath
     */
    private static void deleteTempFile(File file, String filePath) {
        if (file != null) {
            boolean deleteResult = file.delete();
            if (!deleteResult) {
                log.error("file delete error, filePath= {}", filePath);
            }
        }
    }
}
